package com.hmy.uaa.config;

import com.hmy.uaa.common.security.UserIdAuthenticationProvider;
import com.hmy.uaa.common.security.UserIdDetailsService;
import com.hmy.uaa.common.security.UserNameDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;


@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserIdDetailsService userIdDetailsService;

    @Autowired
    private UserNameDetailsService userNameDetailsService;

    @Bean
    public PasswordEncoder passwordEncoder() {
        return PasswordEncoderFactories.createDelegatingPasswordEncoder();
    }


    @Bean
    public AuthenticationProvider userIdAuthenticationProvider() {
        // userIdDetailsService：通过uid查询用户
        UserIdAuthenticationProvider userIdAuthenticationProvider = new UserIdAuthenticationProvider(userIdDetailsService);
        return userIdAuthenticationProvider;
    }

    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(userIdAuthenticationProvider())
                .userDetailsService(userNameDetailsService)
                .passwordEncoder(passwordEncoder());

    }

    /**
     * 使用OAuth的password模式, 必须要有AuthenticationManager这个类
     */
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        AuthenticationManager authenticationManager = super.authenticationManagerBean();
        return authenticationManager;
    }

}
